package com.link.common.core;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component // 必须注册为 Spring Bean
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    // 根据类型获取 Bean
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    // 根据名称获取 Bean
    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

    // 根据名称和类型获取 Bean
    public static <T> T getBean(String beanName, Class<T> clazz) {
        return applicationContext.getBean(beanName, clazz);
    }

    // 检查是否存在某个 Bean
    public static boolean containsBean(String beanName) {
        return applicationContext.containsBean(beanName);
    }
}